/**
 * @description user controller
 */

 const { getUserInfo, createUser, deleteUser, updateUser } = require('../services/user')
 const { SuccessModel, ErrorModel } = require('../model/ResModel')
 const { registerUserNameNotExistInfo, changeInfoFailInfo, deleteUserFailInfo, loginFailInfo, registerFailInfo, registerUserNameExistInfo } =require('../model/ErrorInfo')
 const { doCrypto } = require('../utils/cryp')
 const { APPID, SECRET } = require('../conf/constant')
 const axios = require('axios')
 const Token = require('../utils/token')
 
 let tokenIns = Token.getInstance()

 /**
  * 用户名是否存在
  * @param {string} userName 用户名 
  */
 async function isExist(userName) {
    // 业务逻辑处理
    // 调用services 获取数据
    // 统一返回格式
    const userInfo = await getUserInfo(userName)
    if(userInfo) {
        return new SuccessModel(userInfo)
    }else{
        return new ErrorModel(registerUserNameNotExistInfo)
    }
 }

 /**
  * 注册
  * @param {string} username
  * @param {password} username
  * @param {number} gender
  */
 async function register({ userName, password, gender} ) {
    const userInfo = await getUserInfo(userName)
    if(userInfo) {
        return new ErrorModel(registerUserNameExistInfo)
    }
    // 注册services
    try {
        await createUser({ userName, password: doCrypto(password), gender})
        return new SuccessModel()
    }catch (ex) {
        console.error(ex.message, ex.stack)
        return new ErrorModel(registerFailInfo)
    }
 }

 /**
  * 登录
  */
 async function login (ctx, userName, password) {
    const userInfo = await getUserInfo(userName, doCrypto(password))
    if(!userInfo) {
        return new ErrorModel(loginFailInfo)
    }
    // 登录成功
    if(ctx.session.userInfo == null) {
        ctx.session.userInfo = userInfo
    }
    return new SuccessModel()

 }
  /**
  * 删除当前用户
  */
 async function deleteCurUser (userName) {
    // service
    const result = await deleteUser(userName)
    if(result) {
        return new SuccessModel()
    }
    return new ErrorModel(deleteUserFailInfo)
 }

 // 修改用户信息
 async function changeInfo(ctx, {nickName, city, picture}) {
    const { userName } = ctx.session.userInfo
    if(!nickName) {
        nickName = userName
    }
    const result = await updateUser(
        {
            newNickName: nickName,
            newCity: city,
            newPicture: picture
        },{
            userName
        }
    )
    if(result) {
        Object.assign(ctx.session.userInfo, {nickName, city, picture})
        return new SuccessModel()
    }
    return new ErrorModel(changeInfoFailInfo)
 }

 async function changePassword (userName, password, newPassword) {
    const result = await updateUser(
        {
            newPassword: doCrypto(newPassword),
        },
        {
            userName,
            password: doCrypto(password)
        }
    )
    if(result) {
        return new SuccessModel()
    }
    return new ErrorModel(changeInfoFailInfo)
 }

 async function logout(ctx) {
     delete ctx.session.userInfo
     return new SuccessModel()
 }

 // 绑定微信用户
 async function bindOpenId(ctx, code) {
    const { userName, openid } = ctx.session.userInfo
    const res = await getOpenId(code)
    if(openid) return new SuccessModel()
    const result = await updateUser(
        {
            openid: res.data.openid
        },{
            userName
        }
    )
    if(result) {
        return new SuccessModel()
    }
    return new ErrorModel(changeInfoFailInfo)
 }

 // 获取小程序openid
async function getOpenId (code) {
    return axios.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`)
}

async function sendMessage(ctx, tmplId) {
    const { openid } = ctx.session.userInfo
    console.log(openid)
    const result = await axios.post(`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${tokenIns.getAccessToken()}`, {
        access_token: tokenIns.getAccessToken(),
        touser: openid,
        template_id: tmplId,
        page: 'pages/index/index',
        miniprogram_state: 'developer',
        data: {
            "time1": { "value": '6:00' }, 
            "thing3": { "value": '完成6条任务，遗留1条任务' },
            "thing2": { "value": '完成6条任务，遗留1条任务' },
            "thing4": { "value": '完成6条任务，遗留1条任务' },
            "thing5": { "value": '完成6条任务，遗留1条任务' }

        }
    })
    console.log(result)
    return new SuccessModel()
}

 module.exports = {
    isExist,
    register,
    login,
    deleteCurUser,
    changeInfo,
    changePassword,
    logout,
    bindOpenId,
    sendMessage
 }